// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const subMchId = "1636715260"
const envId = "wjs-4gpwpq5j4372152f"

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const {
    title,
    fee,
    barrel, // 空桶押金
    userOpenId, // 空桶押金
    orderId, // 步梯费
  } = event

  if (title == '空桶押金') {
    return await getPladgePayment(event)
  } else if (title == '步梯费') {
    return await getStepFeePayment(event)
  }
}

async function getStepFeePayment(event) {
  const {
    title,
    fee,
    orderId, // 步梯费
  } = event

  // 读取orders数据
  const res = await db.collection('orders')
    .where({
      _id: orderId
    }).get()

  const order = res.data[0]
  if (!order) return null

  const outTradeNo = createOutTradeNo() // 订单号

  // 获取免鉴权支付参数
  const payMent = await createPayment(title, outTradeNo, Number(fee) * 100)

  // 更新订单
  const nowTime = new Date().getTime()
  await db.collection('orders')
    .where({
      _id: orderId
    })
    .update({
      data: {
        updateTime: nowTime,
        outTradeNo: outTradeNo
      }
    })

  return payMent
}

async function getPladgePayment(event) {
  const {
    title,
    fee,
    barrel, // 空桶押金
    userOpenId, // 空桶押金
  } = event

  // 读取users数据
  const res = await db.collection('users')
    .where({
      _openid: userOpenId
    }).get()
  const user = res.data[0]
  if (!user) return null

  const outTradeNo = createOutTradeNo() // 订单号

  // 获取免鉴权支付参数
  const payMent = await createPayment(user._id, title, outTradeNo, Number(fee) * 100)

  // 更新用户user
  const nowTime = new Date().getTime()
  const payList = (user.barrelPay || {}).list || []
  payList.push({
    pladge: Number(fee),
    outTradeNo: outTradeNo,
    payStatus: 'wait',
    timeCreate: nowTime,
  })
  await db.collection('users')
    .where({
      _openid: userOpenId
    })
    .update({
      data: {
        barrelPay: {
          barrel: Number(barrel),
          list: payList
        }
      }
    })

  return payMent
}

async function createPayment(userId, body, outTradeNo, totalFee) {
  const payment = await cloud.cloudPay.unifiedOrder({
    "body": body,
    "outTradeNo": outTradeNo,
    "spbillCreateIp": "127.0.0.1",
    subMchId, // 商户号
    totalFee, // 分
    envId, // 云环境id
    attach: JSON.stringify({
      title: body,
      userId
    }),
    "functionName": "qrPayCallback" // 支付回调云函数
  })

  return payment
}

const createOutTradeNo = () => {
  let outTradeNo = new Date().getTime() // 获取当前13位时间戳
  let numStr = '0123456789';
  let randomStr = '';
  for (let i = (32 - 13); i > 0; --i) {
    randomStr += numStr[Math.floor(Math.random() * numStr.length)];
  }
  outTradeNo += randomStr
  return outTradeNo
}